import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Transaction;

import model.Employee;
import model.Location;
import model.Stay;
import model.enums.StayType;
import model.enums.TrainingType;

/**
 * Copyright [2012] [Энхтөр Энхтөр]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Copyright [2012] [Энхтөр Энхтөр]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
 * applicable law or agreed to in writing, software distributed under the
 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
 * OF ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * Саатлын табын контоллер класс
 * 
 * @author Энхтөр Энхтөр
 * @version 1.0
 * @since 2012-01-27
 */
public class StayController extends Controller
{

	private static final long	serialVersionUID	= -950879054922231326L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		super.doGet(request, response);
	}

	public void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		ServletContext sc = getServletContext();
		RequestDispatcher rd = sc.getRequestDispatcher("/main");
		rd.forward(request, response);
	}

	/**
	 * Саатлын хэсгийн үндсэн дэлгэц
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String html = getViewHtml("stay", "index");
		html = html.replaceAll("\\{stay\\_list\\}", getStayList());
		renderView(html, response);
	}

	/**
	 * @return Саатлын жагсаалт
	 */
	public String getStayList()
	{
		String list = "";
		ArrayList<Stay> stays = Stay.getAllStaysDescByStartEnd(getSession());
		for (Stay stay : stays)
		{
			list += getStayListRow(stay, false);
		}
		return list;
	}

	/**
	 * @param stay
	 * @param ajax
	 * @return Сааталын жагсаалтны элемент
	 */
	public String getStayListRow(Stay stay, boolean ajax)
	{
		String row = "";
		if ( !ajax )
			row += "<tr id=\"text\" stay_row=\"" + stay.getId() + "\" class=\"stay-" + stay.getId() + "\">";
		row += "<td>" + stay.getEmployee().getName() + "</td>";
		row += "<td>" + getStayTypeMore(stay) + "</td>";
		row += "<td>" + StaticMethods.getFormattedDate(stay.getStart()) + "</td>";
		row += "<td>" + StaticMethods.getFormattedDate(stay.getEnd()) + "</td>";
		row += "<td>" + stay.getLocation().getName() + "</td>";
		row += "<td><img style=\"cursor: pointer\" src=\"{path}images/edit.png\" id=\"edit_stay\" stayid=\"" + stay.getId() + "\"/></td>";
		row += "<td><img style=\"cursor: pointer\" src=\"{path}images/delete.png\" id=\"delete_stay\" stayid=\"" + stay.getId() + "\"/></td>";
		if ( !ajax )
			row += "</tr>";
		row = row.replaceAll("\\{path\\}", StaticMethods.PATH);
		return row;
	}

	/**
	 * @param stay
	 * @return Саатлын төрөл
	 */
	public String getStayTypeMore(Stay stay)
	{
		return stay.getStayType().getStayType() + " " + (stay.getStayType().equals(StayType.TRAINING) ? " [ " + stay.getTrainingType().getTrainingType() + " ] " : "");
	}

	/**
	 * Саатал хадгалах диалог
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void dialogStay(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		long stayid = Long.parseLong(getParameter("stayid") != null ? getParameter("stayid") : "-1");
		boolean flag = (stayid == -1) ? false : true;
		Stay stay = flag ? ((Stay) getObjectByPk(Stay.class, stayid)) : null;
		String dialog_html = getViewHtml("stay", "dialog");
		// employee id
		dialog_html = dialog_html.replaceAll("\\{stay\\_id\\}", stayid + "");

		dialog_html = dialog_html.replaceAll("\\{select\\_stay\\_employee\\}", getStayEmployeeList(stay, flag));

		dialog_html = dialog_html.replaceAll("\\{select\\_stay\\_type\\}", getStayTypeList(stay, flag));

		boolean training = flag && stay.getStayType().equals(StayType.TRAINING);
		dialog_html = dialog_html.replaceAll("\\{select\\_stay\\_training\\_type\\}", getStayTrainingTypeList(stay, training));
		dialog_html = dialog_html.replaceAll("\\{training\\_type\\_visible\\}", training ? "" : ("style=\"display: none;\""));

		dialog_html = dialog_html.replaceAll("\\{select\\_stay\\_location\\}", getStayLocationList(stay, flag));

		dialog_html = dialog_html.replaceAll("\\{value\\_stay\\_start\\_date\\}", flag ? StaticMethods.getFormattedDateForDate(stay.getStart()) : "");
		dialog_html = dialog_html.replaceAll("\\{value\\_stay\\_start\\_time\\}", flag ? StaticMethods.getFormattedDateForHourAndMin(stay.getStart()) : "");
		dialog_html = dialog_html.replaceAll("\\{value\\_stay\\_end\\_date\\}", flag ? StaticMethods.getFormattedDateForDate(stay.getEnd()) : "");
		dialog_html = dialog_html.replaceAll("\\{value\\_stay\\_end\\_time\\}", flag ? StaticMethods.getFormattedDateForHourAndMin(stay.getEnd()) : "");
		renderView(dialog_html, response);
	}

	/**
	 * @param stay
	 * @param flag
	 * @return Саатал хадгалах диалогийн үйлчилэгчдийн жагсаалт
	 */
	public String getStayEmployeeList(Stay stay, boolean flag)
	{
		StringBuilder dialogHtml = new StringBuilder();
		for (Employee employee : Employee.getAllEmployeeByFlyTimeASCAndNameASC(getSession()))
		{
			boolean selected = flag && stay.getEmployee().getId() == employee.getId();
			dialogHtml.append("<option " + (selected ? "selected=\"selected\"" : "") + " value=\"" + employee.getId() + "\">" + employee.getName() + "</option>");
		}
		return dialogHtml.toString();
	}

	/**
	 * @param stay
	 * @param flag
	 * @return Саатал хадгалах диалогийн төрлийн жагсаалт.
	 */
	public String getStayTypeList(Stay stay, boolean flag)
	{
		StringBuilder dialogHtml = new StringBuilder();
		for (StayType stayType : StayType.values())
		{
			boolean selected = flag && stay.getStayType() == stayType;
			dialogHtml.append("<option " + (selected ? "selected=\"selected\"" : "") + " value=\"" + stayType.name() + "\">" + stayType.getStayType() + "</option>");
		}
		return dialogHtml.toString();
	}

	/**
	 * @param stay
	 * @param flag
	 * @return Саатал хадгалах диалогийн сургалтын төрлийн жагсаалт.
	 */
	public String getStayTrainingTypeList(Stay stay, boolean training)
	{
		StringBuilder dialogHtml = new StringBuilder();
		for (TrainingType trainingType : TrainingType.values())
		{
			boolean selected = training && stay.getTrainingType() == trainingType;
			dialogHtml.append("<option " + (selected ? "selected=\"selected\"" : "") + " value=\"" + trainingType.name() + "\">" + trainingType.getTrainingType() + "</option>");
		}
		return dialogHtml.toString();
	}

	/**
	 * @param stay
	 * @param flag
	 * @return Саатал хадгалах диалогийн байршилын жагсаалт.
	 */
	public String getStayLocationList(Stay stay, boolean flag)
	{
		StringBuilder dialogHtml = new StringBuilder();
		for (Location location : Location.getAllLocation(getSession()))
		{
			boolean selected = flag && stay.getLocation().getId() == location.getId();
			dialogHtml.append("<option " + (selected ? "selected=\"selected\"" : "") + " value=\"" + location.getId() + "\">" + location.getName() + "</option>");
		}
		return dialogHtml.toString();
	}

	/**
	 * Саатал хадгалах
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@SuppressWarnings("deprecation")
	public void saveStay(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		Transaction transaction = getSession().beginTransaction();
		try
		{
			long stayid = Long.parseLong(getParameter("stayid"));
			boolean flag = stayid == -1 ? false : true;
			Stay stay = flag ? ((Stay) getObjectByPk(Stay.class, stayid)) : (new Stay());

			stay.setEmployee((Employee) getObjectByPk(Employee.class, Long.parseLong(getParameter("employee"))));
			stay.setStayType(StayType.valueOf(getParameter("staytype")));
			stay.setTrainingType(getParameter("trainingtype") == null ? null : TrainingType.valueOf(getParameter("trainingtype")));
			stay.setStart(new Date(getParameter("start_date")));
			stay.setEnd(new Date(getParameter("end_date")));
			stay.setLocation((Location) getObjectByPk(Location.class, Long.parseLong(getParameter("location"))));

			if ( flag )
			{
				getSession().merge(stay);
				transaction.commit();
				renderView(getStayListRow(stay, true), response);
			}
			else
			{
				getSession().save(stay);
				transaction.commit();
				renderView(getStayList(), response);
			}
		}
		catch (Exception exception)
		{
			exception.printStackTrace();
			if ( transaction != null )
				transaction.rollback();
			renderView("0", response);
		}
	}

	/**
	 * Саатал устгах.
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void deleteStay(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		Transaction transaction = getSession().beginTransaction();
		try
		{
			long stayid = Long.parseLong(getParameter("stayid"));
			Stay stay = (Stay) getObjectByPk(Stay.class, stayid);
			getSession().delete(stay);
			transaction.commit();
			renderView("1");
		}
		catch (Exception exception)
		{
			exception.printStackTrace();
			if ( transaction != null )
				transaction.rollback();
			renderView("0");
		}
	}
}
